<template>
    <div style="margin-top: 20px;">
        <div style="display: flex; justify-content: space-evenly;">
            <el-select
                clearable
                v-model="type"
                placeholder="选择房型"
                style="width: 250px"
            >
                <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
            <el-select
                clearable
                v-model="peopleNum"
                placeholder="选择人数"
                style="width: 250px"
            >
                <el-option
                    v-for="item in options2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
            <el-button style="background-color: brown; color: white; width: 150px;" @click="findBySearch">搜索</el-button>
            <el-button style="background-color: brown; color: white; width: 150px;" @click="goAdd">新增房型</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%; margin-top: 30px;" :row-style="{ height: '100px'}">
            <el-table-column
                v-for="column in columns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
            >
                <!-- 自定义列内容，用于显示图片 -->
                <template #default="scope">
                    <template v-if="column.prop === 'roomImage'">
                        <img :src="getImageUrl(scope.row[column.prop])" alt="暂无图片" style="width: 100px; height: auto;" />
                    </template>
                    <template v-else-if="column.prop === 'delete'">
                        <el-button style="background-color: brown; color: white; width: 100px;" @click="goDelete(scope.row.id)">删除</el-button>
                    </template>
                    <template v-else-if="column.prop === 'upload'">
                        <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/api/photo/upload"
                            :on-success="(response) => handleUploadSuccess(response)"
                            :on-error="handleUploadError"
                            :before-upload="beforeUpload"
                            :data="{ id: scope.row.id }"
                        >
                            <el-button style="background-color: brown; color: white;">点击上传</el-button>
                        </el-upload>
                    </template>
                    <!-- 如果这个列不是roomImage，则使用这个模板渲染其他列的数据 -->
                    <template v-else>
                        {{ scope.row[column.prop] }}
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 30px; display: flex; justify-content: center;">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="sizePage"
                :page-sizes="pageSize"
                :size="size"
                :disabled="disabled"
                :background="background"
                layout="total, prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue';
import { ElMessage } from 'element-plus'; 
import request from "@/utils/request";
import { useRouter } from 'vue-router'
const router = useRouter();
import { useStore } from 'vuex';
const store = useStore();

const currentPage = ref(1);
const sizePage = ref(5);
const type = ref();
const peopleNum = ref();
const total = ref()

const options1 = ref([]);
const options2 = ref([]);
const tableData = ref([]);

const columns = ref([
    { prop: 'roomImage', label: '图片' },
    { prop: 'type', label: '房型' },
    { prop: 'peopleNum', label: '可住人数' },
    { prop: 'bedNum', label: '床位数' },
    { prop: 'price', label: '房价' },
    { prop: 'reserveRoom', label: '已订' },
    { prop: 'sumRoom', label: '总量' },
    { prop: 'delete', label: '删房' },
    { prop: 'upload', label: '上传图片' }
]);

// 查询全部
const findAll = async() => {
    try {
        const res = await request.get('/room/findAll');
        if(res.code === '0') {
            // 获取总条数
            total.value = res.data.length;
            const types = res.data.map(el => el.type); // 提取每个元素中的type字段
            const uniqueTypes = [...new Set(types)]; // 去重，再转成数组（无重，可省）
            // 获取所有的房型绑定到下拉选择框
            options1.value = uniqueTypes.map(type => ({ // 格式化为el-select需要的形式
                lable: type,
                value: type
            }));
            const peopleNums = res.data.map(el => el.peopleNum); 
            const uniquePeopleNum = [...new Set(peopleNums)]; 
            // 获取所有的可住人数绑定到下拉选择框
            options2.value = uniquePeopleNum.map(peopleNum => ({ 
                lable: peopleNum,
                value: peopleNum
            }))
        }
    } catch(error) {
        ElMessage({
            message: error,
            type: 'error'
        });
    }
}

// 分页查询
const findByPage = async(currentPage, sizePage) => {
    try {
        const res = await request.get('/room/findByPage', {
            params: {
                current: currentPage.value,
                size: sizePage.value
            }
        });
        if(res.code === '0') {
            tableData.value = res.data.records;
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            });
        }
    } catch(error) {
        ElMessage({
            message: error,
            type: 'error'
        });
    }
}

// 条件查询
const findBySearch = async() => {
    try {
        currentPage.value = 1;
        const res = await request.get('/room/findBySearch', {
            params: {
                current: currentPage.value,
                size: sizePage.value,
                type: type.value,
                peopleNum: peopleNum.value
            }
        });
        if(res.code === '0') {
            tableData.value = res.data.records;
            total.value = res.data.total;
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            });
        }
    } catch(error) {
        ElMessage({
            message: error,
            type: 'error'
        });
    }
}

onBeforeMount(async() => {
    await findAll();
    await findByPage(currentPage, sizePage);
});

// 选择页数
const handleCurrentChange = async(newPage) => {
    currentPage.value = newPage;
    await findByPage(currentPage, sizePage);
}

// 回显图片
const getImageUrl = (fileName) => {
    return `http://localhost:8080/api/photo/get?fileName=${fileName}`;
}

const goDelete = async(id) => {
    try {
        const res = await request.post('/room/delete', {
            id: id
        });
        if(res.code === '0') {
            ElMessage({
                message: '删除成功',
                type: 'success'
            });
            setTimeout(() => {
                location.reload();
            }, 1000); 
        }
    } catch(error) {
        ElMessage({
            message: error,
            type: 'error'
        });
    }
}

const goAdd = () => {
    router.push('/admin/addRoom')
}

const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/'); // 检查是否是图片
    if (!isImage) {
        ElMessage.error('上传文件必须是图片!');
    }
    return isImage;
};

const handleUploadError = () => {
    ElMessage.error('上传失败');
};

const handleUploadSuccess = (response) => {
    console.log(response);
    if (response.code === '0') {
        ElMessage({
            message: '上传成功',
            type: 'success'
        });
        setTimeout(() => {
            location.reload();
        }, 1000);
    } else {
        ElMessage.error(response.msg || '上传失败');
    }
};

</script>

<style lang="less" scoped>

</style>